/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Scene, SceneConfig } from "../../ArkAnalyzer/src";
import { GraphBuilder } from "../../Ark2Graph/graphBuilder";
import { describe, expect, test, beforeAll, afterAll } from "@jest/globals";
import path from "path";
import fs from "fs";
import { Connection } from "../../Ark2Graph/Client";

const testConfigs = [
  "TestCallGraphConfig.json",
  "TestNoCallGraphConfig.json"
];

describe.each(testConfigs)("CG Builder Test with %s", (configFile: string) => {
  let client: any;
  let graphBuilder: GraphBuilder;
  let CGCount: any;
  
  const CGquery = `.E().has('type', 'cg').count()`;
  const cypherBatch = 'g';

  beforeAll(async () => {
    client = await Connection.getClient();
    const configPath = path.resolve(__dirname, `../test_config/${configFile}`);
    graphBuilder = new GraphBuilder(client, configPath);
    const configfile = JSON.parse(fs.readFileSync(configPath, "utf-8"));
    const filePath = configfile.fileTestConfigPath;
    let config: SceneConfig = new SceneConfig();
    config.buildFromJson(filePath);
    config.buildFromProjectDir(config.getTargetProjectDirectory());
    let scene = new Scene();
    scene.buildSceneFromProjectDir(config);
    graphBuilder.setScene(scene);

    // Only build CPG for TestCallGraphConfig
    if (configFile === "TestCallGraphConfig.json") {
      await graphBuilder.buildCPG();
      CGCount = await client.submit(cypherBatch + CGquery);
    } else {
      CGCount = { _items: [0] }; // Default to 0 edges for NoCallGraph
    }
  });

  afterAll(async () => {
    //if (client) {
      await client.close();
    //}
  });

  test("should initialize GraphBuilder correctly", () => {
    expect(graphBuilder).toBeDefined();
  });

  // Expected values for each test config
  const expectedValues = {
    "TestCallGraphConfig.json": { cg: 1 },
    "TestNoCallGraphConfig.json": { cg: 0 }
  };

  test("should build CG edges correctly", () => {
    expect(CGCount._items[0]).toBe(
      expectedValues[configFile as keyof typeof expectedValues].cg
    );
  });
});
